(ns pe.p42)

(defn triangle [n]
  (int (* 0.5 n (inc n))))

(defn triangle-step [data]
  [(inc (first data)) (triangle (inc (first data)))])

(defn tr-seq []
  (map last (iterate triangle-step [1 1])))

(defn alphapos [#^java.lang.Character c]
  (- (Character/getNumericValue c) 9))

(defn triangle? [n]
  (= (last (take-while #(<= % n) (tr-seq))) n))

(defn tokenize-str [s]
  (map #(.trim %) (seq (.split #"," s))))

(defn remove-quotes [strings]
  (map #(.substring % 1 (dec (.length %))) strings))

(defn tokenize-file [fname]
  (remove-quotes (tokenize-str (slurp fname))))

(defn sum-letters [word]
  (reduce + (map alphapos (seq word))))

(defn p42 [fname]
  (let [words (tokenize-file fname)]
    (count (filter triangle? (map sum-letters words)))))

(println (p42 "c:/words.txt"))